﻿using DemountCIM.Framework;
using DemountCIM.Framework.PLC;
using DeMountCIM.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;
using WpfUIDLL.MessageBox;
using WpfUIDLL.WFControls;
using Timer = System.Timers.Timer;

namespace DemountCIM.View
{
    /// <summary>
    /// DebugView.xaml 的交互逻辑
    /// </summary>
    public partial class DebugView : UserControl
    {
        private Timer _timer;
        private PlcData plcData;

        private List<TextBlock> TextBlocks;
        private List<Run> TextRuns;

        public DebugView()
        {
            InitializeComponent();

            plcData = new PlcData();
            CreatePlcControl();

            _timer = new Timer();
            _timer.Enabled = true;
            _timer.Interval = 400;
            _timer.Elapsed += _timer_Elapsed;
            _timer.AutoReset = true;
        }

        private void _timer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                PlcDataUpdate();
            }));
        }



        #region PLC

        // 创建PLC实时数据控件
        private void CreatePlcControl()
        {
            List<string> plcNames = new List<string>
            {
                "晶托到达脱胶#1工位：",
                "晶托到达RFID#1工位：",
                "晶托离开脱胶#1工位：",
                "晶托到达脱胶#2工位：",
                "晶托到达RFID#2工位：",
                "晶托离开脱胶#2工位：",
                "晶托到达树脂板码垛工位：",
                "晶托到达RFID#3工位：",
                "晶托离开码垛工位：",
                "晶托到达铲胶机工位：",
                "晶托离开铲胶机工位：",
                "晶托到达清洗机工位：",
                "晶托离开清洗机工位：",
                "晶托小车#1#上料请求：",
                "晶托小车#1#下料请求：",
                "晶托小车#1#到位信号：",
                "晶托AMR#1#到位信号：",
                "晶托小车#2#上料请求：",
                "晶托小车#2#下料请求：",
                 "晶托小车#2#到位信号：",
                "晶托AMR#2#到位信号：",
                 "树脂板小车上料请求：",
                "树脂板小车下料请求：",
                 "树脂板小车到位信号：",
                "树脂板AMR到位信号：",
                "脱胶机#1工作状态：",
                "脱胶机#2工作状态：",
                "树脂板码垛工作状态：",
                "铲胶机工作状态：",
                "清洗机工作状态：",

            };

            TextBlocks = new List<TextBlock>(plcNames.Count);
            TextRuns = new List<Run>(plcNames.Count);

            for (int i = 0; i < plcNames.Count; i++)
            {
                TextBlock textBlock = new TextBlock();
                Run run = new Run(plcNames[i]);
                textBlock.Inlines.Add(run);
                Run run1 = new Run("");
                textBlock.Inlines.Add(run1);
                TextRuns.Add(run1);
                TextBlocks.Add(textBlock);
                DataCanvas.Children.Add(textBlock);
            }

        }

        private void PlcDataUpdate()
        {
            var Ctrl = MachineCtrl.GetInstance();
            txtPlcIP.Text = Ctrl.PlcIP();
            txtPlcPort.Text = Ctrl.PlcPort().ToString();
            lblPlcConnectState.Text = Ctrl.PlcIsConnected() ? "已连接" : "已断开";

            Ctrl.PlcReadData(ref plcData);

            int i = 0;
            string On = "⚫";
            string Off = "⚪";
            string[] workStatus = new string[] { "错误", "工作中", "待机" };
            TextRuns[i++].Text = plcData.demounter1Station[0] ? On : Off;
            TextRuns[i++].Text = plcData.demounter1Station[1] ? On : Off;
            TextRuns[i++].Text = plcData.demounter1Station[2] ? On : Off;
            TextRuns[i++].Text = plcData.demounter2Station[0] ? On : Off;
            TextRuns[i++].Text = plcData.demounter2Station[1] ? On : Off;
            TextRuns[i++].Text = plcData.demounter2Station[2] ? On : Off;
            TextRuns[i++].Text = plcData.palletizingStation[0] ? On : Off;
            TextRuns[i++].Text = plcData.palletizingStation[1] ? On : Off;
            TextRuns[i++].Text = plcData.palletizingStation[2] ? On : Off;
            TextRuns[i++].Text = plcData.removeGlueStation[0] ? On : Off;
            TextRuns[i++].Text = plcData.removeGlueStation[1] ? On : Off;
            TextRuns[i++].Text = plcData.cleaningStation[0] ? On : Off;
            TextRuns[i++].Text = plcData.cleaningStation[1] ? On : Off;
            TextRuns[i++].Text = plcData.plateCartLoadASK[0] ? On : Off;
            TextRuns[i++].Text = plcData.plateCartUnloadASK[0] ? On : Off;
            TextRuns[i++].Text = plcData.plateCartArrived[0] ? On : Off;
            TextRuns[i++].Text = plcData.plateAMRArrived[0] ? On : Off;
            TextRuns[i++].Text = plcData.plateCartLoadASK[1] ? On : Off;
            TextRuns[i++].Text = plcData.plateCartUnloadASK[1] ? On : Off;
            TextRuns[i++].Text = plcData.plateCartArrived[1] ? On : Off;
            TextRuns[i++].Text = plcData.plateAMRArrived[1] ? On : Off;
            TextRuns[i++].Text = plcData.beamCartLoadASK ? On : Off;
            TextRuns[i++].Text = plcData.beamCartUnloadASK ? On : Off;
            TextRuns[i++].Text = plcData.beamCartArrived ? On : Off;
            TextRuns[i++].Text = plcData.beamAMRArrived ? On : Off;
            TextRuns[i++].Text = plcData.demounter1State == (int)PlcDef.Error ? workStatus[0] :
                (plcData.demounter1State == (int)PlcDef.InProcess ? workStatus[1] : workStatus[2]);

            TextRuns[i++].Text = plcData.demounter2State == (int)PlcDef.Error ? workStatus[0] :
               (plcData.demounter2State == (int)PlcDef.InProcess ? workStatus[1] : workStatus[2]);

            TextRuns[i++].Text = plcData.palletizingState == (int)PlcDef.Error ? workStatus[0] :
            (plcData.palletizingState == (int)PlcDef.InProcess ? workStatus[1] : workStatus[2]);

            TextRuns[i++].Text = plcData.removeGlueState == (int)PlcDef.Error ? workStatus[0] :
            (plcData.removeGlueState == (int)PlcDef.InProcess ? workStatus[1] : workStatus[2]);

            TextRuns[i++].Text = plcData.cleaningState == (int)PlcDef.Error ? workStatus[0] :
            (plcData.cleaningState == (int)PlcDef.InProcess ? workStatus[1] : workStatus[2]);
        }


        private void btnPlcConnect_Click(object sender, RoutedEventArgs e)
        {
            string error = "";
            if (MachineCtrl.GetInstance().PlcConnect(ref error))
            {
                ShowMsgBox.ShowDialog("PLC连接成功！", MessageType.MsgMessage);
                return;
            }
            ShowMsgBox.ShowDialog($"PLC连接失败，原因：【{error}】！", MessageType.MsgWarning);

        }

        private void btnPlcDisconnect_Click(object sender, RoutedEventArgs e)
        {
            string error = "";
            if (MachineCtrl.GetInstance().PlcDisConnect(ref error))
            {
                ShowMsgBox.ShowDialog("PLC断开连接成功！", MessageType.MsgMessage);
                return;
            }
            ShowMsgBox.ShowDialog($"PLC断开连接失败，原因：【{error}】！", MessageType.MsgWarning);
        }

        #endregion

        #region RFID

        private void AnoleComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var index = (sender as AnoleComboBox).SelectedIndex;

            this.rfidIP.Content = MachineCtrl.GetInstance().RfidIP(index);
            this.rfidPort.Content = MachineCtrl.GetInstance().RfidPort(index);
            this.rfidStatus.Content = MachineCtrl.GetInstance().RfidIsConnected(index) ? "已连接" : "已断开";
            uidLbl.Content = MachineCtrl.GetInstance().RfidGetUID(rfidCbx.SelectedIndex);


        }

        private void connectButton_Click(object sender, RoutedEventArgs e)
        {
            var index = rfidCbx.SelectedIndex;
            if (MachineCtrl.GetInstance().RfidConnect(index))
            {
                ShowMsgBox.ShowDialog("RFID连接成功！", MessageType.MsgQuestion);
            }
            else
            {
                ShowMsgBox.ShowDialog("RFID连接失败！", MessageType.MsgWarning);
            }
            this.rfidStatus.Content = MachineCtrl.GetInstance().RfidIsConnected(index) ? "已连接" : "已断开";
            uidLbl.Content = MachineCtrl.GetInstance().RfidGetUID(rfidCbx.SelectedIndex);
        }

        private void disconnectButton_Click(object sender, RoutedEventArgs e)
        {
            MachineCtrl.GetInstance().RfidDisConnect(rfidCbx.SelectedIndex);

            this.rfidStatus.Content = MachineCtrl.GetInstance().RfidIsConnected(rfidCbx.SelectedIndex) ? "已连接" : "已断开";
        }

        private void readButton_Click(object sender, RoutedEventArgs e)
        {

            rfidContent.Document.Blocks.Clear();
            uidLbl.Content = MachineCtrl.GetInstance().RfidGetUID(rfidCbx.SelectedIndex);
            if (MachineCtrl.GetInstance().RfidReadCarrierID(rfidCbx.SelectedIndex, out string data))
            {
                string data1 = data.Replace("\0", "");
                rfidContent.AppendText(data1);
            }
            else
            {
                ShowMsgBox.ShowDialog($"读取失败：原因【{data}】", MessageType.MsgWarning);
            }
        }

        #endregion

        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (!(bool)e.NewValue)
            {
                _timer.Stop();
            }
            else
            {
                _timer.Start();
            }
        }

        private void DataCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //int rowCount = 5;
            int columnCount = 3;
            double textBlockWidth = this.DataCanvas.ActualWidth / columnCount;
            double textBlockHeight = 30;


            for (int i = 0; i < TextBlocks.Count; i++)
            {
                int curRow = i / columnCount;
                int curColumn = i % columnCount;

                Canvas.SetTop(TextBlocks[i], curRow * textBlockHeight);
                Canvas.SetLeft(TextBlocks[i], curColumn * textBlockWidth);
            }

        }
    }
}
